package controller;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.ProductBean;
import model.ProductService;


import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.validator.DynaValidatorForm;

import view.ProductActionForm;

public class ProductAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DynaValidatorForm form1 = (DynaValidatorForm) form;
		ProductBean bean = new ProductBean();
		
		bean.setId((String)form1.get("id"));
		bean.setPrice((String)form1.get("price"));
		bean.setExpire((String)form1.get("expire"));
		bean.setName((String)form1.get("name"));
		bean.setMake((String)form1.get("make"));
		HttpSession session = request.getSession();
		ProductService ps = (ProductService) session.getAttribute("pservice");
		String tmp = (String) form1.get("prodation");
		ActionErrors errors = new ActionErrors();

		if ("Insert".equals(tmp)) {
			ProductBean result = ps.insert(bean);
			if (result == null) {
				errors.add("product", new ActionMessage(
						"product.sqlerror.insert"));
				request.setAttribute(Globals.ERROR_KEY, errors);
				
			}
				request.setAttribute("Insert", result);
				return mapping.findForward("product");
					
			
		} else if ("Update".equals(tmp)) {
			ProductBean result = ps.update(bean);
			if (result == null) {
				errors.add("product", new ActionMessage(
						"product.sqlerror.update"));
				request.setAttribute(Globals.ERROR_KEY, errors);
			}
			request.setAttribute("Update", result);
			return mapping.findForward("product");
		} else if ("Delete".equals(tmp)) {
			int i = ps.delete(bean);
			if (i != 1) {
				errors.add("product", new ActionMessage(
						"product.sqlerror.delete"));
				request.setAttribute(Globals.ERROR_KEY, errors);
			}
			request.setAttribute("Delete", i);
			return mapping.findForward("product");
		} else if ("Select".equals(tmp)) {
			List<String[]> list = ps.select(bean);
			if (list == null) {
				errors.add("display", new ActionMessage(
						"product.sqlerror.select"));
				request.setAttribute(Globals.ERROR_KEY, errors);
			}
			request.setAttribute("Select", list);
			return mapping.findForward("select");

		} else {
			return mapping.findForward("error");

		}

	}

}
